// pages/order/orderlist.js
import api from '../../../api/api.js'
import utils from '../../templates/loader/loader.js'
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderlist: [],
    empty: {
      isEmpty: false,
      type: "order",
      text: "没有更多订单了"
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    this.loader = utils.loader(this, {
      data: "loader",
      toast: true,
      size: 50,
      borderWidth: 3
    });
    //var loader2 = utils.loader(this);
    that.loadData(options, function (res) {
      that.loader.close()
      //判断数据是否为空
      if (res.rows.length <= 0) {
        var empty = that.data.empty
        empty.isEmpty = true
        that.setData({
          empty: empty
        })
      }
      that.TForderStatus(res.rows) //转换状态
      that.setData({
        orderlist: res.rows
      })
    });
  },
  loadData: function (options, callback) {
    var that = this
    that.loader.open();
    var title = "全部订单";
    api.getUser({
      done: (user) => {
        var jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":"' + user.id + '"}}'
        that.data.userInfo = user
        switch (options.type) {
          case "0":
            title = "待付款"
            api.getOrder_0({
              method: 'POST',
              data: {
                REQ_MESSAGE: jsonStr
              },
              success: (res) => {
                if (typeof callback == "function")
                  callback(res);
                // that.orderCallBack(res)
              },
              fail: () => {
                that.loader.open("获取订单失败");
              }
            })
            break;
          case "1":
            title = "待发货"
            api.getOrder_1({
              method: 'POST',
              data: {
                REQ_MESSAGE: jsonStr
              },
              success: (res) => {
                if (typeof callback == "function")
                  callback(res);
                // that.orderCallBack(res)
              },
              fail: () => {
                that.loader.open("获取订单失败");
              }
            })
            break;
          case "2":
            title = "待收货"
            api.getOrder_2({
              method: 'POST',
              data: {
                REQ_MESSAGE: jsonStr
              },
              success: (res) => {
                if (typeof callback == "function")
                  callback(res);
                // that.orderCallBack(res)
              },
              fail: () => {
                that.loader.open("获取订单失败");
              }
            })
            break;
          case "3":
            title = "待评价"
            break;
          default:
            api.getOrder({
              method: 'POST',
              data: {
                REQ_MESSAGE: jsonStr
              },
              success: (res) => {
                if (typeof callback == "function")
                  callback(res);
                // that.orderCallBack(res)
              },
              fail: () => {
                that.loader.open("获取订单失败");
              }
            })
            break;
        }
        wx.setNavigationBarTitle({
          title: title
        })
      }
    })
  },
  TForderStatus: function (orderStatus) {
    orderStatus.forEach(function (item) {
      if (item.orderStatus == null) {
        switch (item.paymentStatus) {
          case "0":
            item.orderStatusText = "待付款";
            break;
          case "1":
            item.orderStatusText = "待发货";
            break;
        }
      } else {
        switch (item.orderStatus) {
          case "0":
            item.orderStatusText = "待付款";
            break;
          case "1":
            item.orderStatusText = "待发货";
            break;
          case "2":
            item.orderStatusText = "待收货";
            break;
          case "3":
            item.orderStatusText = "已收货";
            break;
          case "4":
            item.orderStatusText = "已取消";
            break;
        }
      }

    });
  },
  cancelOrder: function (e) {
    var that = this
    var selfData = e.currentTarget.dataset
    wx.showModal({
      title: '提示',
      content: '确定取消订单？',
      confirmColor: "#e30c26",
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
          })
          var jsonStr = '{ "REQ_HEAD":{ "SIGN":"null" },"REQ_BODY": { "id": "' + selfData.orderid + '", "userId": "' + that.data.userInfo.id + '" }}'
          api.cancelOrder({
            method: 'POST',
            data: {
              REQ_MESSAGE: jsonStr
            },
            complete: (res) => {
              wx.hideLoading()
              that.loader.close()
              if (res.statusCode == "200") {
                if (res.data.REP_BODY.RSPCOD == "000000") {
                  that.data.orderlist.splice(selfData.index, 1)
                  wx.showToast({
                    title: '取消订单成功',
                    icon: 'success',
                    duration: 2000
                  })
                  if (that.data.orderlist.length <= 0) {
                    var empty = that.data.empty
                    empty.isEmpty = true
                    that.setData({
                      empty: empty,
                      orderlist: that.data.orderlist
                    });
                    return;
                  }
                  that.setData({
                    orderlist: that.data.orderlist
                  })
                  
                } else {
                  wx.showToast({
                    title: '取消订单失败',
                    image: '/image/ico/error-ico.png',
                    duration: 2000
                  })
                }
              } else {
                wx.showToast({
                  title: '取消订单失败',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            }
          })
        }
      }
    })

  },
  getRefund: function (e) {
    var that = this;
    var json = '{"REQ_HEAD":{ "SIGN":"null" },"REQ_BODY": { "orderId": "' + e.currentTarget.dataset.orderid + '","infoId":"' + e.currentTarget.dataset.infoid+'", "userId": "' + that.data.userInfo.id + '" }}'
    wx.showModal({
      title: '提示',
      content: '确定退款？',
      confirmColor: "#e30c26",
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            mask:true
          })
          api.getRefund({
            method: 'POST',
            data: {
              REQ_MESSAGE: json
            },
            complete: (res) => {
              console.log(res)
              wx.hideLoading()
              if (res.statusCode == 200) {
                if (res.data.REP_BODY.RSPCOD == "000000") {
                  wx.showToast({
                    title: '提交成功',
                    icon: 'success',
                    duration: 3000
                  })
                  that.data.orderlist.forEach(function (item) {
                    if (e.currentTarget.dataset.orderid == item.id) {
                      item.refundStatus = 2;
                    }
                  });
                  that.setData({
                    orderlist: that.data.orderlist
                  })
                } else {
                  if (res.data.REP_BODY.RSPCOD){
                    wx.showModal({
                      title: '提示',
                      content: res.data.REP_BODY.RSPCOD,
                      confirmColor: "#e30c26"
                    })
                  }else{
                    wx.showToast({
                      title: '退款失败',
                      image: '/image/ico/error-ico.png',
                      duration: 2000
                    })
                  }
                }
              } else {
                wx.showToast({
                  title: '退款失败',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            }
          })
        }
      }
    })
  },
  pay: function (e) {
    wx.showLoading({
      mask:true
    })
    var that = this
    wx.login({
      success: function (data) {
        api.payOrder({
          method: 'POST',
          data: {
            orderId: e.currentTarget.dataset.orderno,
            code: data.code,
            userId:that.data.userInfo.id
          },
          complete: (res) => {
            wx.hideLoading()
            if (res.statusCode == 200) {
              if (res.data) {
                wx.requestPayment({
                  'timeStamp': res.data.timeStamp,
                  'nonceStr': res.data.nonceStr,
                  'package': res.data.packageValue,
                  'signType': 'MD5',
                  'paySign': res.data.sign,
                  'success': function (res) {
                    console.log("pay", res);
                    if (res.errMsg == "requestPayment:ok") {
                      that.data.orderlist.forEach(function (item, index) {
                        if (item.orderNo == e.currentTarget.dataset.orderno) {
                          that.data.orderlist.splice(index, 1)
                        }
                      });
                      that.setData({
                        orderlist: that.data.orderlist
                      })
                      // wx.redirectTo({
                      //   url: '/pages/order/orderlist/orderlist?type=1',
                      // })
                      wx.showToast({
                        title: '支付成功!',
                        icon: 'success',
                        duration: 2000
                      })
                    } else {
                      wx.showToast({
                        title: '支付失败!',
                        image: '/image/ico/error-ico.png',
                        duration: 2000
                      })
                    }
                  },
                  'fail': function (res) {
                    if (res.errMsg == "requestPayment:fail cancel") {
                      // wx.redirectTo({
                      //   url: '/pages/order/orderlist/orderlist?type=0',
                      // })
                    } else {
                      wx.showToast({
                        title: '支付失败!',
                        image: '/image/ico/error-ico.png',
                        duration: 2000
                      })
                    }
                    console.log("payFail", res);
                  }
                })
              } else {
                wx.showToast({
                  title: '缺少参数!',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            }
          },
          fail: (res) => {
            wx.showToast({
              title: '支付失败!',
              image: '/image/ico/error-ico.png',
              duration: 2000
            })
          }
        })
      }
    })
  },
  confirmOrder: function (e) {
    var that=this;
    wx.showModal({
      title: '提示',
      content: '确定收货？',
      confirmColor: "#e30c26",
      success: function (res) {
        var json = '{"REQ_HEAD":{ "SIGN":"null" },"REQ_BODY": { "id": "' + e.currentTarget.dataset.orderid + '","infoId":"' + e.currentTarget.dataset.infoid+'"}}'
        if (res.confirm) {
          wx.showLoading({
            mask:true
          })
          api.confirmOrder({
            method: 'POST',
            data: {
              REQ_MESSAGE: json
            },
            complete: (res) => {
              wx.hideLoading();
              if (res.statusCode == 200) {
                if (res.data.REP_BODY.RSPCOD == "000000") {
                  that.data.orderlist.splice(e.currentTarget.dataset.index, 1);
                  wx.showToast({
                    title: '收货成功!',
                    icon: 'success',
                    duration: 2000
                  });
                  if (that.data.orderlist.length<=0){
                    var empty = that.data.empty
                    empty.isEmpty = true
                    that.setData({
                      empty: empty,
                      orderlist: that.data.orderlist
                    });
                    return;
                  }
                  that.setData({
                    orderlist: that.data.orderlist
                  });
                }else{
                  wx.showToast({
                    title: '收货失败!',
                    image: '/image/ico/error-ico.png',
                    duration: 2000
                  });
                }
              }else{
                wx.showToast({
                  title: '收货失败!',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                });
              }
            }
          })
        }
      }
    })
  },
  goDetail:function(e){
    var data = this.data.orderlist[e.currentTarget.dataset.index];
    wx.navigateTo({
      url: '/pages/order/orderdetail/orderdetail?jsonData=' + JSON.stringify(data)
    })
  }
})